package com.example.api.mall.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.db.nosql.redis.RedisDS;
import cn.hutool.json.JSONUtil;
import com.example.common.core.constant.CachePreConstant;
import com.example.entity.domain.user.User;

/**
 * @name: TokenUtils
 * @description:
 * @author: xw.s
 * @date: 2021/6/3-16:07
 */
public class TokenUtils {

    /**
     * 创建token
     * @param user
     * @return
     */
    public static String createToken(User user){
        if (null == user || null == user.getId()){
            return null;
        }
        String token = SecureUtil.md5(user.getId().toString());
        RedisDS.create().getJedis().set(getKey(token), JSONUtil.toJsonStr(user));
        //TODO 设置日期
        return token;
    }

    /**
     * 获取key
     * @param token
     * @return
     */
    private static String getKey(String token){
        return CachePreConstant.TOKEN_PREFIX + token;
    }

    /**
     * 验证token
     * @param token
     * @return
     */
    public static boolean verifyToken(String token) {
        String jsonStr = RedisDS.create().getJedis().get(getKey(token));
        if (StrUtil.isBlank(jsonStr)){
            return false;
        }
        return true;
    }

    /**
     * 获取用户信息
     * @param token
     * @return
     */
    public static User getUser(String token) {
        String jsonStr = RedisDS.create().getJedis().get(getKey(token));
        if (StrUtil.isBlank(jsonStr)){
            return null;
        }
        User user = JSONUtil.toBean(jsonStr, User.class);
        if (null == user.getId()){
            return null;
        }
        return user;
    }

}
